<?php
/**
 * Created by PhpStorm.
 * User: chuyun
 * Date: 2018/8/14
 * Time: 9:15
 */

namespace App\Controllers;


use App\Models\Group;
use App\Models\User;
use Interop\Container\ContainerInterface;
use Slim\Http\Request;
use Respect\Validation\Validator as v;

class GroupController extends BaseController
{
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
    }

    public function getOptionList(Request $request){
        $list = Group::select('id','title')->get()->toArray();
        return $this->jsonWithData(1,'OK',$list);

    }

    public function groupList(Request $request){
        $list   = $this->getGroupLoop(0);
        return $this->jsonWithData(1,'OK',$list);
    }

    public function groupStore(Request $request){
        $params = $request->getParsedBody();
        //校验
        if(isset($params['id']) && $params['id']>0) {
            $validate =  $this->container->validator->validateArray($params,
                [
                    'title' => v::noWhitespace()->notEmpty()->setTemplate('请输入用户组中文名称')
                ]);
            if($validate->failed()){
                $errors = $validate->getErrors();
                foreach ($errors as $item){
                    $message = $item[0];
                    break;
                }
                return $this->json(1005,$message);
            }
            $group = Group::where('id',$params['id'])->first();
            $group->title = $params['title'];
            if($group->save()){
                return $this->json(1,'OK');
            }else{
                return $this->json(1,'修改失败');
            }
        } else {
            $validate =  $this->container->validator->validateArray($params,
                [
                    'name'  => v::noWhitespace()->notEmpty()->existsInTable($this->container->db->table('group'), 'name')->setTemplate('同名的用户组已存在或是用户组名为空'),
                    'title' => v::noWhitespace()->notEmpty()->setTemplate('请输入用户组中文名称')
                ]);
            if($validate->failed()){
                $errors = $validate->getErrors();
                foreach ($errors as $item){
                    $message = $item[0];
                    break;
                }
                return $this->json(1005,$message);
            }
            $group = new Group();
            $group->name   = $params['name'];
            $group->title  = $params['title'];
            $group->pid    = isset($params['pid'])&&!empty($params['pid'])?$params['pid']:0;
            if($group->save()){
                return $this->json(1,'OK');
            }else{
                return $this->json(1,'创建失败');
            }
        }
    }

    public function groupDelete(Request $request) {
        $params = $request->getParsedBody();
        if(intval($params['id'])==0){
            return $this->json(1005,'id不合法');
        }
        $tagcount = Group::where('pid',$params['id'])->count();
        if($tagcount){
            return $this->json(0,'该用户组存在子用户组，不允许删除！');
        }

        $adCount = User::where('group_id',$params['id'])->count();
        if($adCount){
            return $this->json(0,'该用户组中存在用户，不允许删除！');
        }
        $ret = Group::where('id',$params['id'])->delete();
        if($ret){
            return $this->json(1,'OK');
        } else {
            return $this->json(0,'删除失败');
        }
    }

    public function getGroupLoop($id){
        $tagsList = Group::where(['pid'=>$id])->get();
        $list     = [];
        $i        = 0;
        foreach ($tagsList as $key => $val){
            $list[$i]['id']    = $val->id;
            $list[$i]['name']  = $val->name;
            $list[$i]['title'] = $val->title;
            $list[$i]['pid']   = $val->pid;
            $children = $this->getGroupLoop($val->id);
            if($children){
                $list[$i]['children'] = $children;
            }
            $i++;
        }
        return $list;
    }
}